<template>
  <div v-show="!books.length">
    <h1>请选择一些您所心仪地书籍放进购物车~</h1>
  </div>
  <div class="shopping-cart" v-show="books.length">
    <h3>购物车</h3>
    <table>
      <tr>
        <th></th>
        <th>商品名称</th>
        <th>单价</th>
        <th>数量</th>
        <th>金额</th>
        <th>操作</th>
      </tr>
      <tr v-for="book in books" :key="book.id">
        <td><img :src="book.imgUrl" alt="" /></td>
        <td>
          <router-link
            :to="{ name: 'book', params: { id: book.id } }"
            target="_blank"
          >
            {{ book.title }}
          </router-link>
        </td>
        <td>{{ currency(book.price) }}</td>
        <td>
          <button @click="handleSubtract(book)">-</button>
          {{ book.quantity }}
          <button @click="handleAdd(book.id)">+</button>
        </td>
        <td>
          {{ currency(cartItemPrice(book.id)) }}
        </td>
        <td>
          <button class="delete" @click="deleteCartItem(book.id)">删除</button>
        </td>
      </tr>
    </table>
    <p>
      <span><button class="checkout" @click="checkout">结算</button></span>
      <span>总价：{{ currency(cartTotalPrice) }}</span>
    </p>
  </div>
</template>

<script>
import { mapGetters, mapState, mapMutations } from "vuex";
export default {
  name: "ShoppingCart",
  inject: ["currency"],
  computed: {
    ...mapState("cart", {
      books: "items",
    }),
    ...mapGetters("cart", ["cartItemPrice", "cartTotalPrice"]),
  },
  methods: {
    itemPrice(price, count) {
      return price * count;
    },
    ...mapMutations("cart", [
      "deleteCartItem",
      "incrementItemQuantity",
      "setCartItems",
    ]),
    handleAdd(id) {
      this.incrementItemQuantity({ id: id, quantity: 1 });
    },
    handleSubtract(book) {
      let quantity = book.quantity - 1;
      if (quantity <= 0) {
        this.deleteCartItem(book.id);
      } else {
        this.incrementItemQuantity({ id: book.id, quantity: -1 });
      }
    },
    checkout() {
      this.$router.push("/check");
    },
  },
};
</script>

<style scoped>
.shopping-cart {
  width: 900px;
  margin: 50px auto;
}
table {
  border: 1px solid #ccc;
  width: 100%;
  border-radius: 10px;
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.301);
  padding: 0 20px;
}
th {
  height: 50px;
}
th,
td {
  text-align: center;
  padding: 30px 0;
  border-bottom: 1px solid #ccc;
}
td {
  flex: 1;
}
span {
  padding: 0 10px;
  line-height: 30px;
  float: right;
}
p {
  margin-top: 50px;
}
button {
  cursor: pointer;
  border: 1px solid#3a8efd;

  color: #3a8efd;
  background: white;
  transition: 0.2s;
}
.delete,
.checkout {
  border-radius: 10px;
  width: 50px;
  height: 30px;
}
button:hover {
  color: white;
  background: #3a8efd;
}
h1,
h3 {
  text-align: center;
}
</style>
